﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Zero.UControl.Component
{
    public class PasswordAttachHelper
    {
        #region 密码附加属性
        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }

        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordAttachHelper), new PropertyMetadata("", OnPasswordChanged));

        private static bool isUpdating = false;

        /// <summary>
        /// 当数据源发生变化时通知View层进行数据更新
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (isUpdating) return;
            if (d is PasswordBox passwordBox)
            {
                passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
                passwordBox.Password = e.NewValue?.ToString();
                passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
            }
        }

        private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            isUpdating = true;
            if (sender is PasswordBox passwordBox)
            {
                string password = passwordBox.Password;
                SetPassword(passwordBox, password);
            }
            isUpdating = false;
        }
        #endregion
    }
}
